package com.example.administrator.wallet.view.activity.mine.Personal.ReceiptInformation.WeChat;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.wallet.R;
import com.example.administrator.wallet.constant.Api;
import com.example.administrator.wallet.intf.IRequestCallback;
import com.example.administrator.wallet.intf.IRequestManager;
import com.example.administrator.wallet.model.bean.AddProceedBean;
import com.example.administrator.wallet.model.bean.DelProceedBean;
import com.example.administrator.wallet.model.bean.GatheringGetListBean;
import com.example.administrator.wallet.model.bean.GetOneBean;
import com.example.administrator.wallet.utils.DimbgUtils;
import com.example.administrator.wallet.utils.RequestFactory;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.example.administrator.wallet.view.activity.mine.Personal.ReceiptInformation.ReceiptInformationActivity;
import com.google.gson.Gson;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.OkHttpFinal;
import cn.finalteam.okhttpfinal.OkHttpFinalConfiguration;
import cn.finalteam.okhttpfinal.RequestParams;
import mvp.presenter.HeaderPresenter;
import mvp.view.IHeaderView;
import okhttp3.Headers;

import static com.example.administrator.wallet.view.fragment.mine.MineFragment.getHttpBitmap;

public class ModifyWeChatActivity extends AppCompatActivity implements IHeaderView {
    private ImageButton mIb_back;
    private TextView mV_title;
    private Button bt_finish,bt_delete;
    private RelativeLayout rl_alipay,activity_new_alipay;
    private EditText ed_alipay_number;

    private View view;
    private HeaderPresenter headerPresenter =  new HeaderPresenter(this, this);
    private File file;
    private static final int MSG_TAKE_PHOTO = 1;
    private GatheringGetListBean.DataBean dataBean;
    private RequestParams params;
    private String id = "";
    private DelProceedBean delProceedBean;
    private File file_photo;
    private GetOneBean getOneBean;
    private List<GetOneBean.DataBean> datas = new ArrayList<>();
    private GetOneBean.DataBean gdataBean;
    private String head;
    private static Bitmap bitmap_head;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_we_chat);

        setStatuColor();
        //传递dataBean
        Intent intent = getIntent();
        id = intent.getStringExtra("id");

        mIb_back = (ImageButton) findViewById(R.id.finish_img);
        mV_title = (TextView) findViewById(R.id.view_title);
        bt_finish = (Button) findViewById(R.id.bt_finish);
        rl_alipay = (RelativeLayout) findViewById(R.id.rl_alipay);
        ed_alipay_number = (EditText) findViewById(R.id.ed_alipay_number);
        activity_new_alipay = (RelativeLayout) findViewById(R.id.activity_new_alipay);
        bt_delete = (Button) findViewById(R.id.bt_delete);

        mIb_back.setVisibility(View.VISIBLE);
        mV_title.setText(R.string.ReceiptInfo);

        final Handler handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        rl_alipay.setBackground(bitmap2Drawable(bitmap_head));
                        break;

                }
            }
        };
        final IRequestManager reqequestManager = RequestFactory.getReqequestManager();
        reqequestManager.httpPost(Api.BaseUrl + Api.Get_One, Api.getGetOne(SharedPrefsUtil.getValue(ModifyWeChatActivity.this, "wallet", "token", ""),id), new IRequestCallback() {
            @Override
            public void onSuccess(String Response) {
                Gson gson = new Gson();
                getOneBean = gson.fromJson(Response, GetOneBean.class);
                if (getOneBean.getCode() == 200){
                    ed_alipay_number.setText(getOneBean.getData().getAccount());
                    head = getOneBean.getData().getQrcode();
                    new Thread() {
                        public void run() {
                            file_photo = saveBitmapFile(getBitMBitmap(head));
                        }
                    }.start();
                    // 显示
                    new Thread() {
                        public void run() {
                            bitmap_head = getHttpBitmap(head);
                            Message msg = handler.obtainMessage();
                            msg.obj = bitmap_head;
                            msg.what = 1;
                            handler.sendMessage(msg);
                        }
                    }.start();
                }else{
                    Toast.makeText(getApplicationContext(),getOneBean.getMessage(),Toast.LENGTH_SHORT).show();
                    onBackPressed();
                }
            }
            @Override
            public void onFailure(String error) {
            }
        });

        rl_alipay.setBackground(Drawable.createFromPath(head));
        rl_alipay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHead();
            }
        });
        bt_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OkHttpFinalConfiguration.Builder builder = new OkHttpFinalConfiguration.Builder();
                OkHttpFinal.getInstance().init(builder.build());
                params = new RequestParams();
                params.addFormDataPart("access_token", SharedPrefsUtil.getValue(ModifyWeChatActivity.this, "wallet", "token", ""));
                params.addFormDataPart("id",id);
                params.addFormDataPart("proceeds_type","wxpay");
                params.addFormDataPart("qrcode",file_photo);
                params.addFormDataPart("account",ed_alipay_number.getText().toString());
                if ("".equals(ed_alipay_number.getText().toString()) | rl_alipay.getBackground() == null){
                    Toast.makeText(getApplicationContext(), R.string.Submissioncannotbeempty,Toast.LENGTH_SHORT).show();
                }else{
                    //微信二维码上传
                    HttpRequest.post("https://wallet.kinlink.cn/api/gathering/up-proceed",params,new BaseHttpRequestCallback<AddProceedBean>(){
                        @Override
                        protected void onSuccess(Headers headers, AddProceedBean addProceedBean) {
                            super.onSuccess(headers, addProceedBean);
                            int code = addProceedBean.getCode();
                            if (code == 200){
                                Toast.makeText(getApplicationContext(),addProceedBean.getMessage(),Toast.LENGTH_SHORT).show();
                                onBackPressed();
                            }else {
                                Toast.makeText(getApplicationContext(),addProceedBean.getMessage(),Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(int errorCode, String msg) {
                            super.onFailure(errorCode, msg);

                        }
                    });
                }

            }
        });

        bt_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final IRequestManager reqequestManager = RequestFactory.getReqequestManager();
                reqequestManager.httpPost(Api.BaseUrl + Api.Del_Proceed, Api.getDel_Proceed(SharedPrefsUtil.getValue(ModifyWeChatActivity.this, "wallet", "token", ""),id), new IRequestCallback() {
                    @Override
                    public void onSuccess(String Response) {
                        Gson gson = new Gson();
                        delProceedBean = gson.fromJson(Response, DelProceedBean.class);
                        if (delProceedBean.getCode() == 200){
                            Toast.makeText(getApplicationContext(),delProceedBean.getMessage(),Toast.LENGTH_SHORT).show();
                            onBackPressed();
                        }else{
                            Toast.makeText(getApplicationContext(),delProceedBean.getMessage(),Toast.LENGTH_SHORT).show();
                        }
                    }
                    @Override
                    public void onFailure(String error) {
                    }
                });
            }
        });
        mIb_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });


    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        startActivity(new Intent(getApplicationContext(),ReceiptInformationActivity.class));
        finish();
        overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_out_anim);
    }
    /**
     * 根据路径 转bitmap
     * @param urlpath
     * @return
     */
    public static Bitmap getBitMBitmap(String urlpath) {

        Bitmap map = null;
        try {
            URL url = new URL(urlpath);
            URLConnection conn = url.openConnection();
            conn.connect();
            InputStream in;
            in = conn.getInputStream();
            map = BitmapFactory.decodeStream(in);
            // TODO Auto-generated catch block
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
    /**
     * 把batmap 转file
     * @param bitmap
     */
    public static File saveBitmapFile(Bitmap bitmap){
        File file=new File(Environment.getExternalStorageDirectory() + "/" + "iMon.jpg");//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
    private void initHead() {
        view = View.inflate(this, R.layout.popup_head, null);
        final Button open_camera = (Button) view.findViewById(R.id.open_camera);
        final Button open_photo = (Button) view.findViewById(R.id.open_photo);
        final Button bt_cancel = (Button) view.findViewById(R.id.bt_cancel);

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                final PopupWindow window = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT, true);
                window.setFocusable(true);
                window.setTouchable(true);
                window.setOutsideTouchable(true);
                window.showAtLocation(activity_new_alipay, Gravity.CENTER, 0, 0);
                Log.e("TAG-----", "OK");
                DimbgUtils.dimBackground(ModifyWeChatActivity.this, 0.5f);
                window.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        DimbgUtils.dimBackground(ModifyWeChatActivity.this, 1.0f);
                    }
                });

                open_camera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Build.VERSION.SDK_INT >= 23) {
                            int checkCallPhonePermission = ContextCompat.checkSelfPermission(ModifyWeChatActivity.this, Manifest.permission.CAMERA);
                            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(ModifyWeChatActivity.this, new String[]{Manifest.permission.CAMERA}, 222);
                                window.dismiss();

                                return;
                            } else {

                                headerPresenter.takePhoto(ModifyWeChatActivity.this);//调用具体方法
                                window.dismiss();

                            }
                        } else {

                            headerPresenter.takePhoto(ModifyWeChatActivity.this);//调用具体方法
                            window.dismiss();

                        }

                        window.dismiss();

                    }
                });
                //相册
                open_photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        headerPresenter.selectFromAlbum();
                        window.dismiss();
                    }
                });
                bt_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        window.dismiss();
                    }
                });
            }
        });

    }
    Drawable bitmap2Drawable(Bitmap bitmap) {
        return new BitmapDrawable(bitmap);
    }
    //返回设置
    public void setHeaderBitmap(Bitmap bitmap) {
        rl_alipay.setBackground(bitmap2Drawable(bitmap));
        file_photo = headerPresenter.getFile(bitmap);
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 点击取消按钮
        if (resultCode == RESULT_CANCELED) {
            return;
        }
        switch (requestCode) {
            case 2:
                Uri uri = data.getData();
                headerPresenter.startPhoto(uri);
                break;
            case 3:
                file = new File(Environment.getExternalStorageDirectory() + "/" + "iMon.jpg");
                headerPresenter.startPhoto(Uri.fromFile(file));
                break;
            case 4:
                if (data != null) {
                    headerPresenter.setView(data);
                }
                break;
            case MSG_TAKE_PHOTO:
                Log.i("main","to do");
                break;
        }
    }
    public void setStatuColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(android.R.color.white));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        setMiuiStatusBarDarkMode(this, true);
        setMiuiStatusBarDarkMode(this, true);
    }

    //设置成白色的背景，字体颜色为黑色。
    public static boolean setMiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean setMeizuStatusBarDarkIcon(Activity activity, boolean dark) {
        boolean result = false;
        if (activity != null) {
            try {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                activity.getWindow().setAttributes(lp);
                result = true;
            } catch (Exception e) {
            }
        }
        return result;
    }
}
